import sys
from MySQLdb import connect
from MySQLdb.cursors import CursorStoreResultMixIn, BaseCursor
from jinja2 import Environment, FileSystemLoader
from config import DATA_SOURCE

class Pojo(dict):

    def __getattr__(self, key):
        return self[key]

    def __setattr__(self, key, value):
        self[key] = value

    def __delattr__(self, key):
        del self[key]

class CursorX(CursorStoreResultMixIn, BaseCursor):

    _fetch_type = 1

    def fetchone(self):
        return Pojo(CursorStoreResultMixIn.fetchone(self))

    def fetchmany(self, size=None):
        return [Pojo(r) for r in CursorStoreResultMixIn.fetchmany(self, size)]

    def fetchall(self):
        return [Pojo(r) for r in CursorStoreResultMixIn.fetchall(self)]

SQL_TYPES = (
        ('int',), 
        ('bigint',),
        ('varchar', 'char'),
        ('datetime',),
        )
JAVA_TYPES = (
        'int',
        'long',
        'String',
        'Date',
        )

def mapper(type):
    for i, t in enumerate(SQL_TYPES):
        if type in t:
            return JAVA_TYPES[i]
    raise Exception('mapper error. type not found type is %s' % (type))

def capitalizex(value):
    if not value: return None
    return value[0].capitalize() + value[1:]

def select(sql, param=None):
    DataSource = Pojo(DATA_SOURCE)
    DataSource.cursorclass = CursorX
    con = connect(**DataSource)
    cursor = con.cursor()
    cursor.execute(sql, param)
    ret = cursor.fetchall()
    cursor.close()
    con.close()
    return ret


def gen(table, tpl='tpl_do.tpl'):
    fs = select('desc %s' % (table,)) 
    do = Pojo()
    do.name = ''.join([i.capitalize() for i in table.split('_')])
    do.attrs = []
    for f in fs:
        attr = Pojo()
        attr.name = ''.join([v if i == 0 else v.capitalize() for i, v in enumerate(f.Field.split('_'))])
        attr.type = mapper(f.Type[0: f.Type.index('(')] if '(' in f.Type else f.Type)
        do.attrs.append(attr)

    env = Environment(loader = FileSystemLoader('.'))
    env.filters['capitalizex'] = capitalizex
    t = env.get_template(tpl);
    return t.render({'do' : do})

if __name__ == '__main__':
    if len(sys.argv) != 2:
        print 'daogen.py table'
        sys.exit(-1)
    print gen(sys.argv[1])
